package com.credithc.signature.job.service;

import com.credithc.signature.common.po.ScheduleLog;
import com.credithc.signature.common.po.Template;
import com.credithc.signature.job.mapper.ScheduleLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.Objects;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年06⽉18⽇<br/>
 * @version：v1.0.0<br>
 */
@Service
@Slf4j
public class ScheduleLogService {

    @Autowired
    ScheduleLogMapper scheduleLogMapper;

    /**
     * 保存定时任务
     *
     * @param requestSn
     */
    public void saveTask(String requestSn) {
        ScheduleLog scheduleLog = queryTask(requestSn);
        if (Objects.isNull(scheduleLog)) {
            ScheduleLog logInfo = new ScheduleLog();
            logInfo.setHandleCount(1);
            logInfo.setRequestSn(requestSn);
            logInfo.setCreateTime(new Date());
            scheduleLogMapper.insert(logInfo);
            log.info("－消息－: requestSn={},失败订单存入定时任务表中等待重签[handleCount={}]", requestSn, logInfo.getHandleCount());
        } else {
            Example example1 = new Example(Template.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("id", scheduleLog.getId());
            ScheduleLog logInfo = new ScheduleLog();
            logInfo.setHandleCount(scheduleLog.getHandleCount() + 1);
            scheduleLogMapper.updateByExampleSelective(logInfo, example1);
            log.info("－消息－: requestSn={},失败订单存入定时任务表中等待重签[handleCount={}]", requestSn, logInfo.getHandleCount());
        }
    }

    /**
     * 获取任务
     *
     * @param requestSn
     * @return
     */
    public ScheduleLog queryTask(String requestSn) {
        Example example = new Example(ScheduleLog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("requestSn", requestSn);
        return scheduleLogMapper.selectOneByExample(example);
    }
}
